package com.ruoyi.business.utils;

import com.ruoyi.business.domain.vo.SchoolTestReportVO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.util.List;

public class WordReportUtil {
    public static byte[] generateSchoolReportWord(SchoolTestReportVO vo) {
        try (XWPFDocument doc = new XWPFDocument(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            // 标题
            XWPFParagraph title = doc.createParagraph();
            title.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun runTitle = title.createRun();
            runTitle.setText(vo.getSchoolName() + "(" + vo.getTestName() + ")体测报告");
            runTitle.setFontSize(22);
            runTitle.setBold(true);
            runTitle.addBreak();

            // 1. 学生男女分布情况
            XWPFParagraph p1 = doc.createParagraph();
            XWPFRun r1 = p1.createRun();
            r1.setText("1. 学生男女分布情况");
            r1.setFontSize(14);
            r1.setBold(true);

            // 外层2列表格，左：分布表，右：饼图（外表格无边框，内表格有边框）
            XWPFTable outerTable = doc.createTable(1, 2);
            outerTable.setWidth("10000");
            // 设置外表格无边框
            outerTable.getCTTbl().getTblPr().unsetTblBorders();
            // 左单元格插入有边框的内表格
            XWPFTable innerTable = doc.createTable(3, 2);
            innerTable.setWidth("3000");
            innerTable.getRow(0).getCell(0).setText("");
            innerTable.getRow(0).getCell(1).setText("人数");
            innerTable.getRow(1).getCell(0).setText("男生");
            innerTable.getRow(1).getCell(1).setText(String.valueOf(vo.getMaleCount()));
            innerTable.getRow(2).getCell(0).setText("女生");
            innerTable.getRow(2).getCell(1).setText(String.valueOf(vo.getFemaleCount()));
            for (int i = 0; i < 3; i++) {
                innerTable.getRow(i).setHeight(800);
            }
            // 清空左单元格默认段落
            outerTable.getRow(0).getCell(0).removeParagraph(0);
            // 插入内表格
            outerTable.getRow(0).getCell(0).getCTTc().addNewTbl().set(innerTable.getCTTbl());
            // 右单元格插入饼图
            outerTable.getRow(0).getCell(1).removeParagraph(0);
            XWPFParagraph piePara = outerTable.getRow(0).getCell(1).addParagraph();
            piePara.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun pieRun = piePara.createRun();
            if (vo.getGenderPieChartImg() != null) {
                pieRun.addPicture(new java.io.ByteArrayInputStream(vo.getGenderPieChartImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "pie.png", Units.toEMU(300), Units.toEMU(200));
            }

            // 删除多余的表格
            doc.removeBodyElement(doc.getPosOfTable(innerTable));

            // 2. 测试完成情况
            XWPFParagraph p2 = doc.createParagraph();
            XWPFRun r2 = p2.createRun();
            r2.setText("2. 测试完成情况");
            r2.setFontSize(14);
            r2.setBold(true);
            // 完成情况表格
            List<List<String>> rows = vo.getCompletionTableRows();
            if (rows != null && !rows.isEmpty()) {
                XWPFTable table2 = doc.createTable(rows.size(), rows.get(0).size());
                table2.setWidth("9000");
                int colCount = rows.get(0).size();
                for (int c = 0; c < colCount; c++) {
                    table2.getRow(0).getCell(c).setWidth("2250");
                }
                for (int i = 0; i < rows.size(); i++) {
                    table2.getRow(i).setHeight(500);
                    List<String> row = rows.get(i);
                    for (int j = 0; j < row.size(); j++) {
                        table2.getRow(i).getCell(j).setText(row.get(j));
                    }
                }
            }

            // 在插入outerTable2前插入一个空行分隔
            XWPFParagraph blankPara = doc.createParagraph();
            blankPara.createRun().addBreak();
            // 外层2列表格，左：分布表，右：饼图（外表格无边框，内表格有边框）
            XWPFTable outerTable2 = doc.createTable(1, 3);
            outerTable2.setWidth("9400");
            // 设置外表格无边框
            outerTable2.getCTTbl().getTblPr().unsetTblBorders();
            // 插入三张柱状图到三个单元格
            // 全体
            outerTable2.getRow(0).getCell(0).removeParagraph(0);
            XWPFParagraph barAllPara = outerTable2.getRow(0).getCell(0).addParagraph();
            barAllPara.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun barAllRun = barAllPara.createRun();
            if (vo.getBarChartAllImg() != null) {
                barAllRun.addPicture(new java.io.ByteArrayInputStream(vo.getBarChartAllImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "bar_all.png", Units.toEMU(160), Units.toEMU(130));
            }
            // 男生
            outerTable2.getRow(0).getCell(1).removeParagraph(0);
            XWPFParagraph barMalePara = outerTable2.getRow(0).getCell(1).addParagraph();
            barMalePara.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun barMaleRun = barMalePara.createRun();
            if (vo.getBarChartMaleImg() != null) {
                barMaleRun.addPicture(new java.io.ByteArrayInputStream(vo.getBarChartMaleImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "bar_male.png", Units.toEMU(160), Units.toEMU(130));
            }
            // 女生
            outerTable2.getRow(0).getCell(2).removeParagraph(0);
            XWPFParagraph barFemalePara = outerTable2.getRow(0).getCell(2).addParagraph();
            barFemalePara.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun barFemaleRun = barFemalePara.createRun();
            if (vo.getBarChartFemaleImg() != null) {
                barFemaleRun.addPicture(new java.io.ByteArrayInputStream(vo.getBarChartFemaleImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "bar_female.png", Units.toEMU(160), Units.toEMU(130));
            }
            // 设置outerTable2左缩进500（使用底层CTTblPr/CTTblWidth）
            org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr tblPr = outerTable2.getCTTbl().getTblPr();
            if (tblPr == null) {
                tblPr = outerTable2.getCTTbl().addNewTblPr();
            }
            org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth indent = tblPr.isSetTblInd() ? tblPr.getTblInd() : tblPr.addNewTblInd();
            indent.setW(new java.math.BigInteger("-500"));
            indent.setType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth.DXA);

            // 在插入"完成项目人员的统计情况"表格后，插入"全校学生总分评级统计表"
            // 插入标题
            XWPFParagraph scoreLevelTitle = doc.createParagraph();
            XWPFRun scoreLevelRun = scoreLevelTitle.createRun();
            scoreLevelRun.setText("3.全校学生总分评级统计表");
            scoreLevelRun.setFontSize(14);
            scoreLevelRun.setBold(true);
            // 插入表格
            List<List<String>> scoreLevelTableRows = vo.getScoreLevelTableRows();
            if (scoreLevelTableRows != null && !scoreLevelTableRows.isEmpty()) {
                XWPFTable scoreLevelTable = doc.createTable(scoreLevelTableRows.size(), scoreLevelTableRows.get(0).size());
                scoreLevelTable.setWidth("9000");
                int colCount = rows.get(0).size();
                for (int c = 0; c < colCount; c++) {
                    scoreLevelTable.getRow(0).getCell(c).setWidth("2250");
                }
                for (int i = 0; i < scoreLevelTableRows.size(); i++) {
                    List<String> row = scoreLevelTableRows.get(i);
                    for (int j = 0; j < row.size(); j++) {
                        scoreLevelTable.getRow(i).getCell(j).setText(row.get(j));
                    }
                }
            }

            // 插入空行
            XWPFParagraph blankPara2 = doc.createParagraph();
            blankPara2.createRun().addBreak();
            // 三列表格
            XWPFTable scoreLevelBarTable = doc.createTable(1, 3);
            scoreLevelBarTable.setWidth("9400");
            scoreLevelBarTable.getCTTbl().getTblPr().unsetTblBorders();
            // 全体
            scoreLevelBarTable.getRow(0).getCell(0).removeParagraph(0);
            XWPFParagraph barAllPara2 = scoreLevelBarTable.getRow(0).getCell(0).addParagraph();
            barAllPara2.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun barAllRun2 = barAllPara2.createRun();
            if (vo.getScoreLevelBarAllImg() != null) {
                barAllRun2.addPicture(new java.io.ByteArrayInputStream(vo.getScoreLevelBarAllImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "score_bar_all.png", Units.toEMU(160), Units.toEMU(130));
            }
            // 男生
            scoreLevelBarTable.getRow(0).getCell(1).removeParagraph(0);
            XWPFParagraph barMalePara2 = scoreLevelBarTable.getRow(0).getCell(1).addParagraph();
            barMalePara2.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun barMaleRun2 = barMalePara2.createRun();
            if (vo.getScoreLevelBarMaleImg() != null) {
                barMaleRun2.addPicture(new java.io.ByteArrayInputStream(vo.getScoreLevelBarMaleImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "score_bar_male.png", Units.toEMU(160), Units.toEMU(130));
            }
            // 女生
            scoreLevelBarTable.getRow(0).getCell(2).removeParagraph(0);
            XWPFParagraph barFemalePara2 = scoreLevelBarTable.getRow(0).getCell(2).addParagraph();
            barFemalePara2.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun barFemaleRun2 = barFemalePara2.createRun();
            if (vo.getScoreLevelBarFemaleImg() != null) {
                barFemaleRun2.addPicture(new java.io.ByteArrayInputStream(vo.getScoreLevelBarFemaleImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "score_bar_female.png", Units.toEMU(160), Units.toEMU(130));
            }

            // 设置scoreLevelBarTable左缩进500（使用底层CTTblPr/CTTblWidth）
            org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr tblPr2 = scoreLevelBarTable.getCTTbl().getTblPr();
            if (tblPr2 == null) {
                tblPr2 = scoreLevelBarTable.getCTTbl().addNewTblPr();
            }
            org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth indent2 = tblPr2.isSetTblInd() ? tblPr2.getTblInd() : tblPr2.addNewTblInd();
            indent2.setW(new java.math.BigInteger("-500"));
            indent2.setType(org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth.DXA);

            // 插入年级成绩统计表格
            XWPFParagraph gradeStatTitle = doc.createParagraph();
            XWPFRun gradeStatRun = gradeStatTitle.createRun();
            gradeStatRun.setText("4. 各年级成绩统计情况");
            gradeStatRun.setFontSize(14);
            gradeStatRun.setBold(true);
            List<List<String>> gradeStatTableRows = vo.getGradeStatTableRows();
            if (gradeStatTableRows != null && !gradeStatTableRows.isEmpty()) {
                XWPFTable gradeStatTable = doc.createTable(gradeStatTableRows.size(), gradeStatTableRows.get(0).size());
                gradeStatTable.setWidth("9000");
                for (int i = 0; i < gradeStatTableRows.size(); i++) {
                    List<String> row = gradeStatTableRows.get(i);
                    for (int j = 0; j < row.size(); j++) {
                        gradeStatTable.getRow(i).getCell(j).setText(row.get(j));
                    }
                }
            }

            // 插入班级成绩统计表格
            XWPFParagraph classStatTitle = doc.createParagraph();
            XWPFRun classStatRun = classStatTitle.createRun();
            classStatRun.setText("5. 各班级成绩统计情况");
            classStatRun.setFontSize(14);
            classStatRun.setBold(true);
            List<List<String>> classStatTableRows = vo.getClassStatTableRows();
            if (classStatTableRows != null && !classStatTableRows.isEmpty()) {
                XWPFTable classStatTable = doc.createTable(classStatTableRows.size(), classStatTableRows.get(0).size());
                classStatTable.setWidth("9000");
                for (int i = 0; i < classStatTableRows.size(); i++) {
                    List<String> row = classStatTableRows.get(i);
                    for (int j = 0; j < row.size(); j++) {
                        classStatTable.getRow(i).getCell(j).setText(row.get(j));
                    }
                }
            }

            // 插入年级等级人数折线图
            XWPFParagraph gradeLineTitle = doc.createParagraph();
            XWPFRun gradeLineRun = gradeLineTitle.createRun();
            gradeLineRun.setText("6. 各年级成绩对比");
            gradeLineRun.setFontSize(14);
            gradeLineRun.setBold(true);
            if (vo.getGradeLevelLineImg() != null) {
                XWPFParagraph chartPara = doc.createParagraph();
                chartPara.setAlignment(ParagraphAlignment.CENTER);
                XWPFRun chartRun = chartPara.createRun();
                chartRun.addPicture(new java.io.ByteArrayInputStream(vo.getGradeLevelLineImg()),
                        XWPFDocument.PICTURE_TYPE_PNG, "grade_level_line.png", Units.toEMU(400), Units.toEMU(200));
            }

            doc.write(baos);
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
} 